from flask import Blueprint, render_template, jsonify, request
from applications.common.utils.rights import authorize
from applications.models import Article
from applications.models import Category
from applications.schemas import ArticleSchema
from sqlalchemy import desc
from applications.common.curd import get_one_by_id
from flask import Markup
import markdown


bp = Blueprint('blog', __name__, url_prefix='/blog')


# 首页
@bp.get('/index')
def index():
    filters = []
    articles = Article.query.filter(*filters).order_by(desc(Article.id)).layui_paginate()
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id)).layui_paginate()
    return render_template('front/blog/index.html', articles=articles, categorys=categorys)

#md转html的方法 
def md2html(content):
	exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc']	
	html = markdown.markdown(content,extensions=exts)
	content = Markup(html)
	return content

# 文章详情
@bp.get('/article/<int:id>')
# @authorize("blog:article:main")
def detail(id):
    r = get_one_by_id(model=Article, id=id)
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id))
    # 不太灵光，base64的图片解析不出来，报错
    # if r:
    #     r.content = md2html(r.content)
    return render_template('front/blog/detail.html', article=r,
                           categorys=categorys)


# 分类列表页
@bp.get('/category/<int:id>')
def category(id):
    filters = [Article.is_del==0]
    if id:
        filters.append(Article.category_id==id)
    articles = Article.query.filter(*filters).order_by(desc(Article.id)).layui_paginate()
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id))
    curr_page = request.args.get('page', type=int) or 1
    limit = 10
    return render_template('front/blog/article.html', articles=articles, 
                           categorys=categorys, category_id=id,
                           curr_page=curr_page, limit=limit)
# 分类列表页
@bp.get('/search')
def search():
    filters = [Article.is_del==0]
    keywords = request.args.get('keywords')
    if keywords:
        filters.append(Article.title.like(f"%{keywords}%"))
    articles = Article.query.filter(*filters).order_by(desc(Article.id)).layui_paginate()
    filters = [Category.is_del==0]
    categorys = Category.query.filter(*filters).order_by(desc(Category.id))
    curr_page = request.args.get('page', type=int) or 1
    limit = 10
    return render_template('front/blog/article.html', articles=articles, 
                           categorys=categorys, category_id=id,
                           curr_page=curr_page, limit=limit)
